<template>
  <div
    v-if="!initializing"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  >
    <div
      class="vc-data-table"
      :style="visual.parseStyle(compStyle)"
    >
      <el-table
        v-loading="loading"
        ref="dataTable"
        v-bind="tableOptions"
        :data="dataList"
        class="vc-data-table-table"
        :style="tableStyle"
        @sort-change="sortChange"
      >
        <el-table-column
          v-if="showCheckbox"
          header-align="center"
          align="center"
          type="selection"
          width="55"
        />
        <el-table-column
          v-if="showIndex"
          header-align="center"
          align="center"
          type="index"
          width="55"
          label="序号"
        />
        <el-table-column
          v-for="(column, index) in columnList"
          :key="index"
          :prop="column.prop"
          v-bind="column.options"
          :show-overflow-tooltip="{
            'effect': 'light',
            'raw-content': false,
            'placement': 'bottom',
            'popper-class': 'padding-10-15'
          }"
        >
          <template #default="{ row }">
            <div
              v-if="column.fieldType === '日期'"
              :style="column.style"
              @click="() => cellClick(column.prop, row)"
            >
              {{row[column.prop] ? date.formatLongDate(row[column.prop], column.format) : ''}}
            </div>
            <div
              v-else-if="column.fieldType === '字典'"
              :style="column.style"
              @click="() => cellClick(column.prop, row)"
            >
              <cc-show-dict :dictCode="column.dictCode" :dictValue="row[column.prop]" />
            </div>
            <div
              v-else-if="column.fieldType === '数字'"
              :style="column.style"
              @click="() => cellClick(column.prop, row)"
            >
              {{tool.formatNumber(row[column.prop], column.point)}}
            </div>
            <div
              v-else-if="column.fieldType === '图片'"
              :style="column.style"
              @click="() => cellClick(column.prop, row)"
            >
              <el-image
                v-if="row[column.prop]"
                style="display: inline-table"
                preview-teleported
                hide-on-click-modal
                :src="imageUrl + row[column.prop]"
                :preview-src-list="[imageUrl + row[column.prop]]"
                fit="scale-down"
              />
            </div>
            <span
              v-else
              class="overflow-ellipsis"
              :style="column.style"
              @click="() => cellClick(column.prop, row)"
            >{{row[column.prop]}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="pagination" class="cc-pagination">
        <el-pagination
          :layout="`total, prev, pager, next,
            ${showJumper ? 'jumper,' : ''}
            ${showSizes ? 'sizes' : ''}`"
          :current-page="queryInfo.pageNumber"
          :page-sizes="[10, 20, 50, 100, 500]"
          :page-size="queryInfo.pageSize"
          :total="dataTotal"
          @current-change="(pageNumber) => queryTableData(pageNumber)"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
  </div>
  <div
    v-else
    v-loading="true"
    element-loading-text=""
    style="min-height: 30px;"
    class="vc-component"
    :style="visual.parseStyle(currNode.currStyle)"
  ></div>
</template>

<script setup>
import { ref, onMounted, inject, getCurrentInstance, nextTick } from 'vue';
import visual from "@/visual/js/visual";
import EventHandler from "@/visual/js/event";
import date from "@/utils/date";
import tool from "@/utils/tool";

const props = defineProps({
  node: Object
});
const initializing = ref(true);
const loading = ref(false);
const currNode = ref(props.node);
const compStyle = ref({});
const dataList = ref([]);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);
const dataTable = ref();
const showCheckbox = ref(false);
const showIndex = ref(false);
const tableOptions = ref({});
const tableStyle = ref('');
const columnList = ref([]);
const imageUrl = ref(import.meta.env.VITE_IMAGE_PATH);
const showJumper = ref(false);
const showSizes = ref(false);

const pagination = ref(false);
const queryInfo = ref({
  pageNumber: 1,
  pageSize: 10
});
const dataTotal = ref(0);

const init = async(styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  compStyle.value = currNode.value.currCompStyle || {};
  pagination.value = currNode.value.compData.dataPage || false;
  queryInfo.value.pageNumber = 1;
  queryInfo.value.pageSize = currNode.value.compData.dataPageSize || 10;
  showCheckbox.value = compStyle.value['header.checkbox'] || false;
  showIndex.value = compStyle.value['header.index'] || false;
  showJumper.value = currNode.value.compData.showJumper || false;
  showSizes.value = currNode.value.compData.showSizes || false;
  initTableStyle();
  initTableOptions();
  initColumnList();
  await nextTick(() => initializing.value = false);
};

const initTableStyle = () => {
  tableStyle.value = '';
  if (compStyle.value['backgroundColor']) {
    tableStyle.value += '--data-table-bg-color: ' + (compStyle.value['backgroundColor'] || 'transparent') + ';';
  }
  if (compStyle.value['hoverColor']) {
    tableStyle.value += '--data-table-tr-hover-bg-color: ' + compStyle.value['hoverColor'] + ';';
  }
  if (compStyle.value['header.color']) {
    tableStyle.value += '--data-table-header-color: ' + (compStyle.value['header.color'] || 'inherit') + ';';
  }
  if (compStyle.value['header.fontSize']) {
    tableStyle.value += '--data-table-header-font-size: ' + compStyle.value['header.fontSize'] + 'px;';
  }
  if (compStyle.value['header.fontWeight']) {
    tableStyle.value += '--data-table-header-font-weight: ' + compStyle.value['header.fontWeight'] + ';';
  }
  if (compStyle.value['header.bgColor']) {
    tableStyle.value += '--data-table-header-bg-color: ' + (compStyle.value['header.bgColor'] || 'inherit') + ';';
  }
  tableStyle.value += '--data-table-header-padding: '
    + (compStyle.value['header.padding'] || '10,5,10,5').split(',').join('px ') + 'px;';
  if (compStyle.value['header.borderColor']) {
    tableStyle.value += '--table-border-color: ' + (compStyle.value['header.borderColor'] || 'inherit') + ';';
  }
  tableStyle.value += '--data-table-body-padding: '
    + (compStyle.value['body.padding'] || '5,5,5,5').split(',').join('px ') + 'px;';
  if (compStyle.value['body.border']) {
    tableStyle.value += '--data-table-body-border: 1px solid ' + compStyle.value['body.border.color'] + ';';
  } else {
    tableStyle.value += '--data-table-body-border: none;';
  }
};

const initTableOptions = () => {
  const options = {};
  options.width = compStyle.value['width'] || '100%';
  options.height = compStyle.value['height'] || '100%';
  options.border = compStyle.value['border'] || false;
  options.stripe = compStyle.value['stripe'] || false;
  tableOptions.value = options;
};

const initColumnList = () => {
  const list = [];
  (compStyle.value.columnList || []).forEach(item => {
    const column = {};
    column.label = item.label;
    column.prop = item.prop;
    column.dictCode = item.dictCode;
    column.fieldType = item.fieldType;
    column.point = item.point;
    column.format = item.format;

    const options = {};
    if (item.autoWidth) {
      options.minWidth = item.width || 10;
    } else {
      options.width = item.width || 10;
    }
    options.sortable = item.sortable ? 'custom' : false;
    options.label = item.label;
    options.headerAlign = item.headerAlign;
    options.align = item.align;
    column.options = options;

    column.style = visual.parseFontStyle(item);
    list.push(column);
  });
  columnList.value = list;
};

const cellClick = (prop, row) => {
  eventHandler.trigger('点击条目事件', row);
};

const sortChange = (column) => {
  if(props.pageSort) {
    return true;
  } else {
    if (column.order === 'ascending') {
      queryInfo.value.sortField = column.prop
      queryInfo.value.sortType = 'asc'
    } else if (column.order === 'descending') {
      queryInfo.value.sortField = column.prop
      queryInfo.value.sortType = 'desc'
    } else {
      queryInfo.value.sortField = null
      queryInfo.value.sortType = null
    }
    queryTableData(1);
  }
};

const handleSizeChange = (pageSize) => {
  queryInfo.value.pageSize = pageSize;
  queryTableData(1);
};

const queryTableData = tool.debounce(async(pageNumber) => {
  if (typeof pageNumber !== 'undefined') {
    queryInfo.value.pageNumber = pageNumber;
  }

  loading.value = true;
  const res = (await visual.loadData(currNode.value.compData, eventHandler, getData(), currNode.value));
  dataList.value = res.data || [];
  dataTotal.value = res.totalRecord || 0;
  await nextTick(() => loading.value = false);
});

const getData = () => {
  return {
    inputParam: currNode.value.inputParam || {},
    dataList: dataTable.value?.getSelectionRows() || [],
    ...queryInfo.value
  };
};

const changeStyle = (styleId) => {
  init(styleId);
};

const refresh = () => {
  queryTableData(1);
};

onMounted(async() => {
  await init();
  queryTableData(1);
  await eventHandler.trigger('初始化事件');
});

defineExpose({ getData, changeStyle, refresh });
</script>

<style scoped lang="scss">
:deep(.el-table) {
  background-color: var(--data-table-bg-color)!important;
  th {
    background-color: var(--data-table-bg-color)!important;
  }
  tr {
    background-color: var(--data-table-bg-color)!important;
  }
  td {
    background-color: var(--data-table-bg-color)!important;
  }
  tr:hover td {
    background-color: var(--data-table-tr-hover-bg-color)!important;
  }
}
:deep(.el-table::before),
:deep(.el-table__inner-wrapper:before) {
  height: 0!important;
}
:deep(.el-table td),
:deep(.el-table th.is-leaf) {
  border-bottom: var(--data-table-body-border)!important;
}
:deep(.el-table th.el-table__cell) {
  background-color: var(--data-table-header-bg-color)!important;
}
:deep(.el-table th.el-table__cell .cell) {
  padding: var(--data-table-header-padding)!important;
}
:deep(.el-table th.el-table__cell .cell) {
  color: var(--data-table-header-color)!important;
}
:deep(.el-table th .cell) {
  font-size: var(--data-table-header-font-size, '14px')!important;
  font-weight: var(--data-table-header-font-weight)!important;
}
:deep(.el-table td .cell) {
  height: unset!important;
  line-height: unset!important;
  padding: var(--data-table-body-padding)!important;
}
.vc-data-table-table .overflow-ellipsis {
  height: unset!important;
  white-space: pre-wrap;
}
.vc-data-table-table .wrap .overflow-ellipsis {
  height: unset!important;
  white-space: pre-wrap;
}
.cc-pagination {
  margin-top: 5px;
  flex-grow: 1;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
</style>